package cqrtplm.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hustcad.plm.pdm.common.util.CommonUtil;
import com.hustcad.plm.pdm.doc.service.TyplmDocumentService;
import com.hustcad.plm.pdm.doc.vo.DocDetails;
import com.hustcad.plm.pdm.doc.vo.DocumentVO;
import com.hustcad.plm.pdm.file.service.TyplmFileHandleService;
import com.hustcad.plm.pdm.filevault.model.vo.FileDataVO;
import com.hustcad.plm.pdm.filevault.service.TyplmContentDataService;
import com.hustcad.plm.pdm.flowbusiness.model.entity.FlowObject;
import com.hustcad.plm.pdm.flowbusiness.model.entity.WorkFlowObjectPackage;
import com.hustcad.plm.pdm.form.model.vo.TyplmFormDataVO;
import com.hustcad.plm.pdm.form.service.TyFormDataExtService;
import com.hustcad.plm.pdm.partbom.dto.PartBomTree;
import com.hustcad.plm.pdm.partbom.service.TyplmPartRelObjectService;
import com.hustcad.plm.pdm.security.util.AESUtil;
import com.hustcad.plm.pdm.user.model.dto.PdmUserDTO;
import com.hustcad.plm.pdm.user.service.TyplmPrincipalService;
import com.hustcad.plm.pdm.workflow.model.entity.UserTaskDTO;
import com.hustcad.plm.pdm.workflow.model.entity.WorkFlowContainerView;
import com.hustcad.plm.pdm.workflow.service.TyplmWorkFlowContainerService;
import com.lark.oapi.okhttp.MediaType;
import com.lark.oapi.okhttp.OkHttpClient;
import com.lark.oapi.okhttp.Request;
import com.lark.oapi.okhttp.RequestBody;
import com.lark.oapi.okhttp.Response;
import com.ty.basic.constant.TableTypeConstrant;
import com.ty.basic.entity.IdentifierEntity;
import com.ty.basic.entity.PrincipalEntity;
import com.ty.basic.entity.filevault.ContentDataDO;
import com.ty.basic.entity.part.PartDO;
import cqrtplm.common.CommonService;
import cqrtplm.dto.DrawingDetailsDTO;
import cqrtplm.dto.SendDrawingDTO;
import cqrtplm.dto.SendSRMDTO;
import cqrtplm.mapper.CADDocumentMapper;
import cqrtplm.mapper.RTPartMapper;
import cqrtplm.service.PointSelectionService;
import cqrtplm.service.RTPartService;
import cqrtplm.vo.MoldDetailVO;
import cqrtplm.vo.MoldProjectVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.assertj.core.util.Lists;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;

@Service
@Slf4j
public class PointSelectionServiceImpl implements PointSelectionService {

    @Resource
    private TyplmWorkFlowContainerService typlmWorkFlowContainerService;

    @Resource
    private TyFormDataExtService tyFormDataExtService;

    @Resource
    private CommonService commonService;

    @Resource
    private TyplmPartRelObjectService typlmPartRelObjectService;

    @Resource
    private RTPartService rtPartService;

    @Resource
    private RTPartMapper rtPartMapper;

    @Resource
    private TyplmPrincipalService typlmPrincipalService;

    @Resource
    private TyplmFileHandleService fileHandleService;

    @Resource
    private TyplmDocumentService typlmDocumentService;

    @Resource
    private CADDocumentMapper cadDocumentMapper;

    @Resource
    private TyplmContentDataService contentDataService;


    public Map<String, String> parseQueryParams(String url) {
        Map<String, String> params = new HashMap<>();
        if (url == null || !url.contains("?")) return params;

        String query = url.split("\\?")[1];
        Arrays.stream(query.split("&"))
                .map(param -> param.split("=", 2))
                .forEach(pair -> {
                    String key = pair[0];
                    String value = pair.length > 1 ? pair[1] : "";
                    params.put(key, value);
                });
        return params;
    }


    @Override
    public void sendSRMPointSelectionData(String workFlowContainerId) {
        WorkFlowContainerView workFlowContainerView = typlmWorkFlowContainerService.getWorkFlowContainerDetailByPrimaryKey(
                new BigInteger(workFlowContainerId));
        if (workFlowContainerView instanceof WorkFlowObjectPackage){
            WorkFlowObjectPackage workFlowObjectPackage=(WorkFlowObjectPackage)workFlowContainerView;
            List<UserTaskDTO> userTaskList = workFlowObjectPackage.getUserTaskList();

            List<FlowObject> flowObjectList = workFlowObjectPackage.getFlowObjectList();
            for (FlowObject flowObject : flowObjectList) {
                BigInteger refObjectOid = flowObject.getRefObjectOid();
                TyplmFormDataVO formDataDetail = tyFormDataExtService.getFormDataDetail(refObjectOid);
                JSONObject jsonObject = formDataDetail.getFormdata();
                MoldProjectVO moldProjectVO = new MoldProjectVO();
                moldProjectVO.setDocCode(flowObject.getRefObjectNumber());
                moldProjectVO.setDocName(flowObject.getRefObjectName());

                // 开发阶段：1->量产, 2->方案设计, 3->方案验证, 4->功能验证，默认为"量产"  todo
                String devStageCode = jsonObject.getString("@DevelopmentStage");
                String developmentStage;
                switch (devStageCode) {
                    case "方案设计": developmentStage = "2"; break;
                    case "方案验证": developmentStage = "3"; break;
                    case "功能验证": developmentStage = "4"; break;
                    case "量产":
                    default: developmentStage = "1"; break;
                }
                moldProjectVO.setOpenStage(developmentStage);

                // 预算类型：1->预算内, 2->预算外，默认为"预算内"
                String budgetTypeCode = jsonObject.getString("@BudgetType");
                String budgetType = "预算内".equals(budgetTypeCode) ? "1" : "2";
                moldProjectVO.setBudgetType(budgetType);

                //项目开发令
                moldProjectVO.setProjectDevOrder(jsonObject.getString("@ProjectDevelopmentOrder"));
                //开模原因
                moldProjectVO.setMoldOpeningReason(jsonObject.getString("@ReasonsMoldOpening"));

                // 模具用途：0->不开模, 1->重庆新开, 2->重庆复制转越南, 3->重庆新开转越南, 4->越南新开, 5->越南复制，默认为"不开模"   todo
                String moldPurposeCode = jsonObject.getString("@TheUsesMolds");
                String moldPurpose;
                switch (moldPurposeCode) {
                    case "重庆新开": moldPurpose = "1"; break;
                    case "重庆复制转越南": moldPurpose = "2"; break;
                    case "重庆新开转越南": moldPurpose = "3"; break;
                    case "越南新开": moldPurpose = "4"; break;
                    case "越南复制": moldPurpose = "5"; break;
                    case "不开模":
                    default: moldPurpose = "0"; break;
                }
                moldProjectVO.setMoldPurpose(moldPurpose);

                //合计摸具金额
                moldProjectVO.setTotalModel("0");
                //EBOM
                moldProjectVO.setEBOM("");
                //类型  todo  默认1：1 开模 2不开模 3衍生
                String type = jsonObject.getString("@TheUsesMolds");
                String typeCode;
                switch (type) {
                    case "2不开模": typeCode = "2"; break;
                    case "3衍生": typeCode = "3"; break;
                    case "开模":
                    default: typeCode = "1"; break;
                }
                moldProjectVO.setType(typeCode);
                boolean isOrg = false;
                if(CollUtil.isNotEmpty(userTaskList)){
                    UserTaskDTO userTaskDTO = userTaskList.get(0);
                    List<PdmUserDTO> userList = userTaskDTO.getUserList();
                    if(CollUtil.isNotEmpty(userList)){
                        PdmUserDTO pdmUserDTO = userList.get(0);
                        //发起人
                        moldProjectVO.setSend_op(pdmUserDTO.getFullname());
                        //发起人手机 telephone
                        moldProjectVO.setSend_tel(jsonObject.getString(pdmUserDTO.getTele()));
                        List<PrincipalEntity> outParent = typlmPrincipalService.getOneOutParentOrg(new PrincipalEntity(new BigInteger(pdmUserDTO.getOid()), TableTypeConstrant.TY_USER_OTYPE));
                        if (CollUtil.isNotEmpty(outParent)){
                            for(PrincipalEntity principalEntity : outParent){
                                String name = principalEntity.getName();
                                if("OPE研发部".equals(name)){
                                    isOrg = true;
                                }
                            }
                        }
                    }
                }
                //发起者部门是否OPE研发部
                moldProjectVO.setSend_ope(isOrg ? "Y" : "N");

                JSONArray formData = jsonObject.getJSONArray("MoldOpeningList");
                Map<String, String> levelMap = buildHierarchyLevels(formData);
                List<MoldDetailVO> moldDetailVOS=new ArrayList<>();
                for (int i = 0; i < formData.size(); i++) {
                    MoldDetailVO moldDetailVO = new MoldDetailVO();
                    moldDetailVO.setID(i + 1);
                    //   formData.getJSONObject(i).getString("L1")
                    moldDetailVO.setLevelL1(levelMap.get(formData.getJSONObject(i).getString("oid")));
                    // L2
                    moldDetailVO.setL2("");
                    // L3
                    moldDetailVO.setL3("");
                    // L4
                    moldDetailVO.setL4("");
                    // L5
                    moldDetailVO.setL5("");
                    // 图样代号
                    moldDetailVO.setDrawingCode(formData.getJSONObject(i).getString("DrawingCode2"));
                    // 零部件名称
                    moldDetailVO.setPartName(formData.getJSONObject(i).getString("ComponentName"));

                    String cadNumber = formData.getJSONObject(i).getString("Blueprint");
                    if(StringUtils.isNotBlank(cadNumber)){
                        DocumentVO documentVO = typlmDocumentService.queryLastDocByNumber(cadNumber);
                        List<FileDataVO> fileListByEntity;
                        if(StringUtils.isNotBlank(documentVO.getOid())){
                            fileListByEntity = this.fileHandleService.getFileListByEntity(new IdentifierEntity(
                                    new BigInteger(documentVO.getOid()),documentVO.getOtype()));
                        }else {
                            String oid = cadDocumentMapper.getLastCADByNumber(cadNumber, "");
                            fileListByEntity = this.fileHandleService.getFileListByEntity(new IdentifierEntity(
                                    new BigInteger(oid), TableTypeConstrant.TY_CADDOC_OTYPE));
                        }
                        if(CollUtil.isNotEmpty(fileListByEntity)){
                            for(FileDataVO fileDataVO : fileListByEntity){
                                String code = workFlowContainerView.getCode();
                                LocalDate currentDate = LocalDate.now();
                                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
                                String formattedDate = currentDate.format(formatter);
                                String filePath = "/drawing/" +  formattedDate + "/" + code + "/";
                                String url = commonService.downloadFileToFtp(new BigInteger(fileDataVO.getFileID()), filePath);
                                // 图纸
                                moldDetailVO.setDrawing(url);
                            }
                        }
                    }

                    // 是否开模
                    String openMoldFlag = formData.getJSONObject(i).getString("Whether to open the mold");
                    moldDetailVO.setOpenMoldFlag(StringUtils.isNotBlank(openMoldFlag) ? openMoldFlag : "1");

                    // 体现内/外
                    String internalOrExternal = formData.getJSONObject(i).getString("ReflectInside/outside");
                    moldDetailVO.setInternalOrExternal(StringUtils.isNotBlank(internalOrExternal) ? internalOrExternal : "1");


                    // 开模预计量
                    moldDetailVO.setMoldOpeningTimePlan(formData.getJSONObject(i).getString("EstimatedAnnualMoldOpeningVolume"));
                    // 模具类型
                    moldDetailVO.setMoldType(formData.getJSONObject(i).getString("MoldType"));
                    // 要求模具送样周期
                    moldDetailVO.setSampleDeliveryCycle(formData.getJSONObject(i).getString("Requirements for molds and sample delivery cycles"));
                    // 开发建议供方
                    moldDetailVO.setRecommendedSupplier(formData.getJSONObject(i).getString("DevelopmentSuggestionProvider"));
                    // 备注
                    moldDetailVO.setRemark(formData.getJSONObject(i).getString("*Remarks"));
                    // 参考图号
                    moldDetailVO.setRefer_graph(formData.getJSONObject(i).getString("ReferencePartDrawing"));
                    // 变化点
                    moldDetailVO.setChange_point(formData.getJSONObject(i).getString("ChangePoint"));

                    List<JSONObject> fileList = new ArrayList<>();
                    JSONArray jsonArray = formData.getJSONObject(i).getJSONArray("pictureupload55753");
                    if(jsonArray != null){
                        for(Object o : jsonArray){
                            JSONObject jsonObject1 = (JSONObject) o;
                            String url = jsonObject1.getString("url");
                            Map<String, String> stringStringMap = parseQueryParams(url);
                            String fileIdStr = stringStringMap.get("fileIdStr");
                            fileIdStr = new String(AESUtil.base64Decode(fileIdStr), StandardCharsets.UTF_8);
                            BigInteger fileId = CommonUtil.stringToBigIntegers(AESUtil.aesDecrypt(fileIdStr));
                            List<ContentDataDO> contentDataDOList = this.contentDataService.queryContentDOsByOIDs(Lists.newArrayList(new BigInteger[]{fileId}));
                            if(CollUtil.isNotEmpty(contentDataDOList)){
                                ContentDataDO contentDataDO = contentDataDOList.get(0);
                                String name = contentDataDO.getName();
                                try {
                                    JSONObject fileJSONObject = new JSONObject();
                                    InputStream inputStream = fileHandleService.downloadFile(fileId);
                                    fileJSONObject.put("img_name",name);
                                    fileJSONObject.put("image",convertToBase64(inputStream,name));
                                    fileList.add(fileJSONObject);
                                    // 图片
                                    moldDetailVO.setFiles(fileList);
                                } catch (Exception e) {
                                    throw new RuntimeException(e);
                                }
                            }
                        }
                    }
                    moldDetailVOS.add(moldDetailVO);
                }
                moldProjectVO.setDetails(moldDetailVOS);
                JSONObject json  = new JSONObject();
                json.put("trans","YILIAN_PlmXdRcv");
                json.put("data",moldProjectVO);
                String jsonStr = JSONObject.toJSONString(json);
                log.info(">>>>sendSRMPointSelectionData>>>>>>json>>>>>{}",jsonStr);
                //发送SRM
                sendDrawingInfoToSrm(jsonStr, "http://222.179.153.58:9191/rt1j/WebAPI/PlmDesign");
            }

        }
    }


    public Map<String, String> buildHierarchyLevels(JSONArray formData) {
        // 创建父子关系映射：partoid -> aoid（子物料OID -> 父物料OID）
        Map<String, String> parentMap = new HashMap<>();
        // 创建节点映射：oid -> 节点对象
        Map<String, JSONObject> nodeMap = new HashMap<>();
        // 创建反向关系映射：partoid -> 子节点oid列表（父物料OID -> 子节点oid列表）
        Map<String, List<String>> childrenMap = new HashMap<>();
        // 存储所有partoid
        Set<String> allPartOids = new HashSet<>();

        // 第一遍遍历：建立关系映射
        for (int i = 0; i < formData.size(); i++) {
            JSONObject item = formData.getJSONObject(i);
            String oid = item.getString("oid");         // 当前数据的OID
            String aoid = item.getString("aoid");       // 父物料的OID
            String partoid = item.getString("partoid"); // 当前物料的OID

            nodeMap.put(oid, item);
            parentMap.put(partoid, aoid);
            allPartOids.add(partoid);
            childrenMap.computeIfAbsent(aoid, k -> new ArrayList<>()).add(oid);
        }

        // 结果映射：oid -> 层级字符串
        Map<String, String> levelMap = new HashMap<>();

        // 找到所有顶级节点（其aoid不在所有partoid中）
        List<String> topLevelOids = new ArrayList<>();
        for (String oid : nodeMap.keySet()) {
            JSONObject node = nodeMap.get(oid);
            String aoid = node.getString("aoid");
            // 如果aoid为空或者aoid不在所有partoid中，则为顶级节点
            if (aoid == null || aoid.isEmpty() || !allPartOids.contains(aoid)) {
                topLevelOids.add(oid);
            }
        }

        // 为顶级节点分配层级
        for (int i = 0; i < topLevelOids.size(); i++) {
            String topLevelOid = topLevelOids.get(i);
            String topLevel = String.valueOf(i + 1);
            buildLevelRecursive(topLevelOid, topLevel, childrenMap, parentMap, nodeMap, levelMap, allPartOids);
        }

        return levelMap;
    }

    private void buildLevelRecursive(String oid, String currentLevel,
                                     Map<String, List<String>> childrenMap,
                                     Map<String, String> parentMap,
                                     Map<String, JSONObject> nodeMap,
                                     Map<String, String> levelMap,
                                     Set<String> allPartOids) {
        // 防止重复访问同一节点导致无限递归
        if (levelMap.containsKey(oid)) {
            return;
        }

        levelMap.put(oid, currentLevel);

        // 获取当前节点的物料OID
        JSONObject currentNode = nodeMap.get(oid);
        if (currentNode == null) return;

        String partoid = currentNode.getString("partoid");

        // 获取当前物料的子节点oid列表
        List<String> childrenOids = childrenMap.get(partoid);
        if (childrenOids != null) {
            for (int i = 0; i < childrenOids.size(); i++) {
                String childOid = childrenOids.get(i);
                String childLevel = currentLevel + "." + (i + 1);
                buildLevelRecursive(childOid, childLevel, childrenMap, parentMap, nodeMap, levelMap, allPartOids);
            }
        }
    }



    public String convertToBase64(InputStream inputStream, String fileName) throws Exception {
        // 读取 InputStream 到字节数组
        ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        byte[] data = new byte[1024];
        int bytesRead;
        while ((bytesRead = inputStream.read(data, 0, data.length)) != -1) {
            buffer.write(data, 0, bytesRead);
        }
        buffer.flush();
        byte[] imageBytes = buffer.toByteArray();

        // 编码为 Base64 字符串
        String base64Image = Base64.getEncoder().encodeToString(imageBytes);

        // 提取扩展名并转换为标准 MIME 类型
        String mimeType = getMimeTypeFromExtension(fileName);

        return "data:" + mimeType + ";base64," + base64Image;
    }

    private String getMimeTypeFromExtension(String fileName) {
        if (fileName == null || fileName.isEmpty()) {
            return "image/png"; // 默认类型
        }

        String extension = "";
        int lastDotIndex = fileName.lastIndexOf('.');
        if (lastDotIndex > 0 && lastDotIndex < fileName.length() - 1) {
            extension = fileName.substring(lastDotIndex + 1).toLowerCase();
        }

        switch (extension) {
            case "png":
                return "image/png";
            case "jpg":
            case "jpeg":
                return "image/jpeg";
            case "gif":
                return "image/gif";
            case "bmp":
                return "image/bmp";
            case "svg":
                return "image/svg+xml";
            case "webp":
                return "image/webp";
            default:
                return "image/png"; // 安全兜底
        }
    }




    @Override
    public void sendSRMMoldRepairData(String workFlowContainerId) {
        WorkFlowContainerView workFlowContainerView = typlmWorkFlowContainerService.getWorkFlowContainerDetailByPrimaryKey(
                new BigInteger(workFlowContainerId));
        if (workFlowContainerView instanceof WorkFlowObjectPackage){
            WorkFlowObjectPackage workFlowObjectPackage = (WorkFlowObjectPackage) workFlowContainerView;
            List<FlowObject> flowObjectList = workFlowObjectPackage.getFlowObjectList();
            SendSRMDTO sendSRMDTO = new SendSRMDTO();
            sendSRMDTO.setTrans("Graph-ToDo");
            List<SendDrawingDTO> sendDrawingDTOList = new ArrayList<>();

            for (FlowObject flowObject : flowObjectList) {
                BigInteger refObjectOid = flowObject.getRefObjectOid();
                TyplmFormDataVO formDataDetail = tyFormDataExtService.getFormDataDetail(refObjectOid);
                JSONObject jsonObject = formDataDetail.getFormdata();
                JSONArray jsonArray = jsonObject.getJSONArray("subform47946");
                //--------------------------------------------------------------
                for(int i=0;i<jsonArray.size();i++){
                    String code = jsonArray.getJSONObject(i).getString("radio73127");
                    String number = code.substring(0,code.indexOf(","));
                    PartDO partDO = rtPartMapper.queryLatestPartByNumberAndView(number, "Design", "");
                    String oid = partDO.getOid().toString();
                    LocalDate currentDate = LocalDate.now();
                    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
                    String formattedDate = currentDate.format(formatter);
                    String filePath = "/drawing/" + formattedDate + "/" + number + "/";
                    if (CollUtil.isEmpty(flowObjectList)) {
                        return;
                    }

                    List<PartBomTree> partBomTreeList = commonService.queryChildPartsNoIba(
                            number,
                            oid,
                            "Design", true,
                            null, "N", true).getPartBomTreeList();
                    PartBomTree partBomTree = partBomTreeList.get(0);
                    SendDrawingDTO sendDrawingDTO = new SendDrawingDTO();
                    sendDrawingDTO.setPushType("2");
                    downloadDrawingAndGetDrawingInfo(partBomTree, sendDrawingDTO, filePath, null);
                    sendDrawingDTOList.add(sendDrawingDTO);
                }
            }
            sendSRMDTO.setList(sendDrawingDTOList);
            if (CollUtil.isNotEmpty(sendDrawingDTOList)) {
                String json = JSONArray.toJSONString(sendSRMDTO);
                log.info("===========提示信息============> 发送图纸信息为：{}", json);
                sendDrawingInfoToSrm(json,"http://192.168.102.40/rt1j/WebAPI/PLM");
            }

        }
    }

    @Override
    public void sendMouldUnloading(String workFlowContainerId) {
        WorkFlowContainerView workFlowContainerView = typlmWorkFlowContainerService.getWorkFlowContainerDetailByPrimaryKey(
                new BigInteger(workFlowContainerId));
        if (workFlowContainerView instanceof WorkFlowObjectPackage){
            WorkFlowObjectPackage workFlowObjectPackage = (WorkFlowObjectPackage) workFlowContainerView;
            List<FlowObject> flowObjectList = workFlowObjectPackage.getFlowObjectList();

            SendSRMDTO sendSRMDTO = new SendSRMDTO();
            sendSRMDTO.setTrans("Graph-ToDo");
            List<SendDrawingDTO> sendDrawingDTOList = new ArrayList<>();

            for (FlowObject flowObject : flowObjectList) {
                BigInteger refObjectOid = flowObject.getRefObjectOid();
                TyplmFormDataVO formDataDetail = tyFormDataExtService.getFormDataDetail(refObjectOid);
                JSONObject jsonObject = formDataDetail.getFormdata();
                JSONArray jsonArray = jsonObject.getJSONArray("MoldOpeningNotice");
                for (int i = 0; i < jsonArray.size(); i++) {
                    String code = jsonArray.getJSONObject(i).getString("input38571");
                    String number = code.substring(0,code.indexOf(","));

                    PartDO partDO = rtPartMapper.queryLatestPartByNumberAndView(number, "Design", "");
                    String oid = partDO.getOid().toString();

                    LocalDate currentDate = LocalDate.now();
                    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
                    String formattedDate = currentDate.format(formatter);
                    String filePath = "/drawing/" + formattedDate + "/" + number + "/";
                    if (CollUtil.isEmpty(flowObjectList)) {
                        return;
                    }

                    List<PartBomTree> partBomTreeList = commonService.queryChildPartsNoIba(
                            number,
                            oid,
                            "Design", true,
                            null, "N", true).getPartBomTreeList();
                    PartBomTree partBomTree = partBomTreeList.get(0);
                    SendDrawingDTO sendDrawingDTO = new SendDrawingDTO();
                    sendDrawingDTO.setPushType("2");
                    downloadDrawingAndGetDrawingInfo(partBomTree, sendDrawingDTO, filePath, null);
                    sendDrawingDTOList.add(sendDrawingDTO);
                }
            }
            sendSRMDTO.setList(sendDrawingDTOList);
            if (CollUtil.isNotEmpty(sendDrawingDTOList)) {
                String json = JSONArray.toJSONString(sendSRMDTO);
                log.info("===========提示信息============> 发送图纸信息为：{}", json);
                sendDrawingInfoToSrm(json,"http://192.168.102.40/rt1j/WebAPI/PLM");
            }
        }
    }

    private void downloadDrawingAndGetDrawingInfo(PartBomTree partBomTree, SendDrawingDTO sendDrawingDTO, String filePath,String type) {
        List<DocDetails> docDetails = this.typlmPartRelObjectService.queryPartRelatedDocInfo(
                new BigInteger(partBomTree.getPartoid()));
        sendDrawingDTO.setPartNumber(partBomTree.getObjectNumber());
        sendDrawingDTO.setOid(partBomTree.getPartoid());
        sendDrawingDTO.setName(partBomTree.getName());
        List<DrawingDetailsDTO> drawingDetails = sendDrawingDTO.getDrawingDetails();
        for (DocDetails docDetail : docDetails) {
            DrawingDetailsDTO drawingDetailsDTO = new DrawingDetailsDTO();
            drawingDetailsDTO.setDrawingCode(docDetail.getNumber());
            drawingDetailsDTO.setDrawingName(docDetail.getName());
            drawingDetailsDTO.setExclusiveSupplier("");
            drawingDetailsDTO.setDrawingReleaseStage("");
            drawingDetailsDTO.setImpInfo("");
            drawingDetailsDTO.setCreateDate(docDetail.getCreationTime());
            drawingDetailsDTO.setLastModifiedDate(docDetail.getModifyTime());
            drawingDetailsDTO.setCreateBy(docDetail.getCreatorFullName());
            drawingDetailsDTO.setUpdateBy(docDetail.getModifierFullName());
            drawingDetailsDTO.setPushType(type);
            drawingDetailsDTO.setTrans("Graph-ToDo");
            drawingDetailsDTO.setVersion(docDetail.getVersion());
            FileDataVO fileDataVO = docDetail.getPrimaryFileList().get(0);
            String url = commonService.downloadFileToFtp(new BigInteger(fileDataVO.getFileID()), filePath);
            drawingDetailsDTO.setDrawingFileUrl(url);
            drawingDetails.add(drawingDetailsDTO);
        }
        HashSet<PartBomTree> children = partBomTree.getChildren();
        if (CollUtil.isNotEmpty(children)) {
            for (PartBomTree child : children) {
                SendDrawingDTO childSendDrawingDTO = new SendDrawingDTO();
                downloadDrawingAndGetDrawingInfo(child, childSendDrawingDTO, filePath, type);
                sendDrawingDTO.getChild().add(childSendDrawingDTO);
            }
        }
    }

    private void sendDrawingInfoToSrm(String json, String url) {
        OkHttpClient client = new OkHttpClient().newBuilder()
                .build();
        MediaType mediaType = MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType, json);
        Request request = new Request.Builder()
                .url(url)
                .method("POST", body)
                .addHeader("appID", "DesigneyJuYW1lIjoiSm9obiIsImFkbWluIjp0cnVlfQ")
                .addHeader("tokenKey", "DesigneyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9")
                .addHeader("Content-Type", "application/json")
                .build();
        try {
            Response response = client.newCall(request).execute();
            JSONObject jsonObject = JSONObject.parseObject(response.body().string());
            if (jsonObject.getString("res").equals("-1")){
                throw new RuntimeException(jsonObject.getString("msg"));
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }


}